package com.springfairytale.qqserver.data;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class XmlUtil {
	public static void writeXml(String rootName, List<Object> list,
			OutputStream output) throws IllegalArgumentException,
			IllegalAccessException, IOException {
		Document doc = new Document();
		Element root = new Element(rootName);
		doc.setRootElement(root);
		for (Object obj : list) {

			Class clz = obj.getClass();
			String clzName = clz.getName();
			Element ele = new Element((clzName.substring(clzName
					.lastIndexOf(".") + 1)).toLowerCase());
			Field[] fieldNames = clz.getDeclaredFields();
			for (Field field : fieldNames) {
				String fieldName = field.getName();
				Element element = new Element(fieldName);
				field.setAccessible(true);
				if ("java.lang.String".equals(field.getType().getName())) {
					element.addContent((String) field.get(obj));
				}
				if ("int".equals(field.getType().getName())) {
					String str = (Integer)field.get(obj)+"";
					element.addContent(str);
				}
				ele.addContent(element);
			}

			root.addContent(ele);
		}

		XMLOutputter outputer = new XMLOutputter();
		outputer.setFormat(Format.getPrettyFormat());
		outputer.output(doc, output);
		output.close();
	}
}
